package cn.com.hp.feature.controller;

import cn.com.hp.feature.response.BaseResponse;
import cn.com.hp.feature.service.IFileService;
import cn.com.hp.feature.util.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hongjuzhu
 * @date 2022/3/28
 */
@Slf4j
@Api(tags = "文件上传下载服务")
@RestController
@RequestMapping("/api/v1/file")
public class FileController {

    @Value("${file.tempFileDir}")
    private String attachRootPath;

    @Autowired
    private IFileService fileService;

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @ResponseBody
    @PostMapping("/uploadfile")
    public BaseResponse uploadFile(@RequestParam("file") MultipartFile file){
        BaseResponse response = new BaseResponse();
        try {
            response.setData(FileUtils.uploadFile(file,attachRootPath));
        } catch (IOException e) {
            log.info("文件上传失败==",e.getMessage());
            log.error(e.getMessage());
        }
        return response;
    }

    /**
     * 下载文件
     *
     * @param filePath
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "文件下载", notes = "文件下载")
    @ResponseBody
    @GetMapping(value = "/download/{date}/{filePath}")
    public void download(
            @PathVariable("date") String date,
            @PathVariable("filePath") String filePath,
            String fileName,
            HttpServletResponse response)
            throws IOException {
        String[] strings = filePath.split("\\.");
        //String fileName = strings[0];//md5转码作为文件名
        log.info("文件名=="+fileName);
        String fileType = "txt";
        if (strings.length > 1) {
            fileType = strings[1];
        }
        fileService.download(response, attachRootPath+ "/" + date + "/" + filePath, fileType,fileName);
    }
}
